package com.corpgovernment.organization.util;

import com.corpgovernment.api.basic.dto.OrgDTO;
import com.corpgovernment.api.organization.model.orguserrelation.request.ListUserOrgRelationForLoginRequest;
import com.corpgovernment.api.organization.model.orguserrelation.response.ListUserOrgRelationForLoginResponse;
import com.corpgovernment.api.organization.model.user.employee.request.FindUserOrgRelationStatusRequest;
import com.corpgovernment.api.permission.soa.IUserPermissionClient;
import com.corpgovernment.api.permission.vo.GetUserPermissionListRequest;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.organization.entity.db.MbUserOrgRelation;
import com.corpgovernment.organization.service.IUserOrgRelationService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * OrganizationUtils
 *
 * @author jiexiangwang
 * @date 2019/10/12
 */
@Component
@Slf4j
public class OrganizationUtils {
	private static IUserPermissionClient userPermissionService;
	private static IUserOrgRelationService userOrgRelationService;

	/**
	 * 生成用户基本信息
	 *
	 * @param uid 员工工号
	 * @return 1 只有一个身份审核通过 0 未审核通过 2 有多个身份审核通过 -1 没有身份 3所有的身份(审核和未审核)
	 */
	public static Map<Integer, List<OrgDTO>> genUserOrgInfo(String uid) {

		ListUserOrgRelationForLoginRequest request = new ListUserOrgRelationForLoginRequest();
		request.setUid(uid);
        List<ListUserOrgRelationForLoginResponse> data = userOrgRelationService.listUserOrgRelationForLogin(request);
        log.info("查询用户uid为[{}]的身份信息响应为[{}]", uid, JsonUtils.toJsonString(data));
        Map<Integer, List<OrgDTO>> result = new HashMap<>(16);
        if (CollectionUtils.isEmpty(data)) {
            result.put(-1, null);
            return result;
        }
        List<OrgDTO> allOrg = orgTransfer(data);
        result.put(3, allOrg);
        // 身份状态 1正常，0待审核
        Map<Integer, List<OrgDTO>> collect = allOrg.stream().collect(Collectors.groupingBy(OrgDTO::getApprovalStatus));
        List<OrgDTO> approvedList = collect.get(1);
        // 有审核通过
        if (CollectionUtils.isNotEmpty(approvedList)) {
            // 只有一个身份审核通过
            if (approvedList.size() == 1) {
                // 直接登录
                result.put(1, approvedList);

            } else {
                // 有多个身份审核通过
                result.put(2, approvedList);
			}
		}
		List<OrgDTO> unApprovedList = collect.get(0);
		if (CollectionUtils.isNotEmpty(unApprovedList)) {
			// 未审核通过
			result.put(0, unApprovedList);
		}
		return result;

	}

	/**
	 * 获取所有审核通过的身份
	 *
	 * @param uid
	 * @return
	 */
	public static List<OrgDTO> getOrgInfoByUid(String uid) {
		if (StringUtils.isBlank(uid)){
			return new ArrayList<>();
		}
		ListUserOrgRelationForLoginRequest request = new ListUserOrgRelationForLoginRequest();
		request.setUid(uid);
		List<ListUserOrgRelationForLoginResponse> list = userOrgRelationService.listUserOrgRelationForLogin(request);
		log.info("查询用户uid为[{}]的身份信息响应为[{}]", uid, JsonUtils.toJsonString(list));
		List<OrgDTO> allOrg = orgTransfer(list);
		return allOrg.stream().filter(e -> e.getApprovalStatus() == 1).collect(Collectors.toList());
	}

	/**
	 * 校验身份
	 *
	 * @param identityFlag 身份标识 只有一个身份审核通过 0 未审核通过 2 有多个身份审核通过 -1 没有身份 3所有的身份(审核和未审核)
	 * @param listMap      身份map
	 * @return 是否
	 */
	public static boolean checkIdentity(int identityFlag, @NonNull Map<Integer, List<OrgDTO>> listMap) {
		return listMap.containsKey(identityFlag);
    }

    /**
     * 用户身份信息转换
     *
     * @param list 组织服务返回的用户身份信息
     * @return 返回给前端的身份信息
     */
    private static List<OrgDTO> orgTransfer(List<ListUserOrgRelationForLoginResponse> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<OrgDTO> orgInfos = new ArrayList<>(list.size());
        for (ListUserOrgRelationForLoginResponse info : list) {
            orgInfos.add(new OrgDTO().setCorpName(info.getCorpName()).setDeptName(info.getOrgName()).setApprovalStatus(
                    info.getApprovalStatus()).setCorpId(info.getCorpId()).setDeptId(info.getOrgId()).setRoleIds(info.getRoleId()));
        }
        return orgInfos;
    }

    /**
     * 校验用户身份是否审核通过
     *
     * @param uid   用户uid
     * @param orgId 用户身份id
     * @return 校验结果 身份状态1正常，0待审核 只有正常状态可以登录
     */
    public static boolean checkIdentity(String uid, String orgId) {
		if (StringUtils.isBlank(uid) || StringUtils.isBlank(orgId)) {
			log.error("uid或者ordId为空");
			return false;
		}
		FindUserOrgRelationStatusRequest findUserOrgRelationStatusRequest = new FindUserOrgRelationStatusRequest();
		findUserOrgRelationStatusRequest.setUid(uid);
		findUserOrgRelationStatusRequest.setOrgId(orgId);
		// 查询用户组织信息,并判断当前组织公司是否可用,不可用不能登录,判断用户身份是否可用
		// 查询关系表
		MbUserOrgRelation mbUserOrgRelation = userOrgRelationService.find(orgId, uid);
		log.info("校验用户身份uid={},orgId={}是否审核通过结果是{}", uid, orgId, JsonUtils.toJsonString(mbUserOrgRelation));
		// 身份状态1正常，0待审核
		return Optional.ofNullable(mbUserOrgRelation).map(MbUserOrgRelation::getStatus).orElse(-1) == 1;
    }


    /**
     * 获取权限列表
     *
     * @param userId 用户id
     * @param orgId  公司id
     * @return 菜单列表
     */
    public static List<String> getMenuList(String userId, String orgId) {
        GetUserPermissionListRequest getUserPermissionListRequest = new GetUserPermissionListRequest();
        getUserPermissionListRequest.setUid(userId);
        getUserPermissionListRequest.setOrgId(orgId);
        try {
            JSONResult<List<String>> jsonResult =
                    userPermissionService.getUserPermissionList(getUserPermissionListRequest);
            log.info("返回菜单 uid={},result={}", userId, JsonUtils.toJsonString(jsonResult));
            return Optional.ofNullable(jsonResult).map(JSONResult::getData).orElse(Collections.emptyList());
        } catch (Exception e) {
            log.info("调用查询菜单接口异常.", e);
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户身份权限列表
     *
     * @param userId 用户id
     * @param orgId  部门id
     * @return 菜单列表
     */
    public static List<String> getIdentityList(String userId, String orgId) {
        GetUserPermissionListRequest getUserPermissionListRequest = new GetUserPermissionListRequest();
        getUserPermissionListRequest.setUid(userId);
        getUserPermissionListRequest.setOrgId(orgId);
		try {
			JSONResult<List<String>> jsonResult = userPermissionService.getUserPermissionListNew(getUserPermissionListRequest);
			log.info("返回菜单 uid={},result={}", userId, JsonUtils.toJsonString(jsonResult));
			return Optional.ofNullable(jsonResult).map(JSONResult::getData).orElse(Collections.emptyList());
		} catch (Exception e) {
			log.info("调用查询菜单接口异常.", e);
		}
		return Collections.emptyList();
	}

	@Autowired
	public void setUserOrgRelationService(IUserOrgRelationService userOrgRelationService) {

		OrganizationUtils.userOrgRelationService = userOrgRelationService;
	}

	@Autowired
	public void setUserPermissionService(IUserPermissionClient userPermissionService) {
		OrganizationUtils.userPermissionService = userPermissionService;
    }
}
